package icu.sehnen.news.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import icu.sehnen.news.entity.MyPage;
import icu.sehnen.news.entity.News;
import icu.sehnen.news.entity.NewsCategory;
import icu.sehnen.news.service.INewsCategoryService;
import icu.sehnen.news.service.INewsService;
import icu.sehnen.common.result.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author icu.sehnen
 * @since 2021-04-26
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    INewsService newsService;
    @Autowired
    INewsCategoryService newsCategoryService;

    @GetMapping("/list")
    public CommonResult findAll(Integer pageNum, Integer pageSize, News news) {
        IPage<News> newsModelList = newsService.findAll(pageNum,pageSize, news);
        return CommonResult.success(newsModelList);
    }

    @GetMapping("/category")
    public CommonResult findCategory() {
        List<NewsCategory> newsCategoryModelList = newsCategoryService.list();
        return CommonResult.success(newsCategoryModelList);
    }

    @PostMapping("/add")
    public CommonResult addNews(News news) {
        Boolean res = newsService.save(news);
        if (res) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @PostMapping("/update")
    public CommonResult update(News news) {
        Boolean res = newsService.updateById(news);
        if (res) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }
    @GetMapping("/find/{id}")
    public CommonResult find(@PathVariable Long id){
        News byId = newsService.findNewsById(id);
        return CommonResult.success(byId);
    }


    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id) {
        Boolean res = newsService.removeById(id);
        if (res) {
            return CommonResult.success();
        }
        return CommonResult.failed();

    }
}
